package com.SinaMicroblogging.TabFocused;

import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

import com.SinaMicroblogging.MainPage;
import com.SinaMicroblogging.PageBase;
import com.SinaMicroblogging.R;
import com.SinaMicroblogging.Extension.DirectMessagesModelAdapter;
import com.SinaMicrobloggingApi.Core.Process.SinaMicrobloggingAPIProcess;
import com.SinaMicrobloggingApi.Model.DirectMessagesModel;
import com.SinaMicrobloggingApi.Model.UserInfoModel;
import com.Util.HttpUtility;

import android.app.AlertDialog;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HeaderViewListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.LayoutParams;

public class MessageTabFocused extends TabFocusedBase {
	private List<DirectMessagesModel> directMessages;
	private DirectMessagesModelAdapter messagesAdapter;
	private ListView listView;
	private Handler handler;
	private Handler getUserAvatarhandler;
	private List<DirectMessagesModel> directMessagesTemp;
	private Boolean refreshable;
	final int REQUEST_COUNT = 10;
	private static Boolean firstFocus = true;
	private int preSelection = -1;
	private static int FIRST_LOCATION = 0;
	private Button sendBtn;
	private EditText content;
	private UserInfoModel currentSelectUser;
	private AlertDialog sendDialog;

	public MessageTabFocused() {
		directMessages = new ArrayList<DirectMessagesModel>();
	}

	public void OnTabFocused(PageBase page) {
		// TODO Auto-generated method stub
		super.OnTabFocused(page);
		if (firstFocus) {
			this.page = page;
			this.context = page.getApplicationContext();
			messagesAdapter = new DirectMessagesModelAdapter(directMessages,
					context);
			messagesAdapter.setReplyClick(replyClick);
			listView = (ListView) this.page.findViewById(R.id.friends);
			handler = createHandler();
			getUserAvatarhandler = createUserAvatarHandler();
			LayoutParams layoutParams = new LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
			TextView textView = new TextView(this.page);
			textView.setPadding(0, 20, 0, 20);
			textView.setId(VIEWMORE_ID);
			textView.setText("Loading...");
			textView.setGravity(Gravity.CENTER);
			textView.setLayoutParams(layoutParams);
			textView.setTypeface(Typeface.DEFAULT_BOLD);
			textView.setTextColor(Color.BLACK);
			textView.setEms(20);
			listView.addFooterView(textView);
			listView.setAdapter(messagesAdapter);
			listView.setOnItemClickListener((MainPage) this.page);
			listView.setOnScrollListener((MainPage) this.page);
			refreshable = true;
			updateMessagesList();
			Log.i("messages", "update");
			firstFocus = false;
		}
	}

	private void updateMessagesList() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				MessageTabFocused.this.directMessagesTemp = getMessagesInfo();
				Message message = new Message();
				message.what = MessageTabFocused.this.directMessagesTemp == null ? API_ACCESS_ERROR
						: API_ACCESS_SUCCESS;
				MessageTabFocused.this.getHandler().sendMessage(message);
			}

		}).start();
	}

	public Handler getHandler() {
		return handler;
	}

	public Handler getUserAvatarHandler() {
		return getUserAvatarhandler;
	}

	private Handler createHandler() {
		Handler handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {
				case API_ACCESS_SUCCESS:
					if (directMessagesTemp != null) {
						filterAndAddMsg();
						MessageTabFocused.this.messagesAdapter
								.notifyDataSetChanged();
						getUserListAvatar();
						getViewMoreTextView().setText("View More");
						MessageTabFocused.this.refreshable = true;
					} else {
						MessageTabFocused.this.page
								.showToast("All of messages have been shown!");
					}
					break;
				case API_ACCESS_ERROR:
					getViewMoreTextView().setText("View More");
					MessageTabFocused.this.page.showToast("Server error!");
					MessageTabFocused.this.refreshable = true;
					break;
				default:
					break;
				}
			}
		};
		return handler;
	}

	private Handler createUserAvatarHandler() {
		Handler handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {
				case 1:
					Log.i("sinaweibo", "avatarList");
					MessageTabFocused.this.messagesAdapter
							.notifyDataSetChanged();
					break;
				default:
					break;
				}
			}
		};
		return handler;
	}

	private List<DirectMessagesModel> getMessagesInfo() {
		UserInfoModel currentUser = super.page.getCurrentUser();

		return SinaMicrobloggingAPIProcess.getDirectMessages(currentUser
				.getAccessToken(), currentUser.getAccessTokenSecret(),
				REQUEST_COUNT);
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (arg2 == listView.getCount() - 1) {
			if (refreshable) {
				refreshable = false;
				getViewMoreTextView().setText("Loading...");
				updateMessagesList();
			}
		} else {
			HeaderViewListAdapter headerAdatper = (HeaderViewListAdapter) arg0
					.getAdapter();
			DirectMessagesModelAdapter adapter = (DirectMessagesModelAdapter) headerAdatper
					.getWrappedAdapter();
			DirectMessagesModel messageModel = (DirectMessagesModel) adapter
					.getItem(arg2);
			currentSelectUser = messageModel.getSender();
			boolean expandable = messageModel.getExpandable();
			messageModel.setExpandable(!expandable);
			if (preSelection != -1 && preSelection != arg2) {
				messageModel = (DirectMessagesModel) adapter
						.getItem(preSelection);
				messageModel.setExpandable(false);
			}
			adapter.notifyDataSetChanged();
			preSelection = arg2;
		}
	}

	View.OnClickListener sendBtnClick = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			String contentValue = content.getText().toString();
			UserInfoModel currentUser = MessageTabFocused.this.page
					.getCurrentUser();
			DirectMessagesModel message = SinaMicrobloggingAPIProcess
					.sendMessage(currentUser.getAccessToken(), currentUser
							.getAccessTokenSecret(), currentSelectUser.getId(),
							contentValue);

			String msg = message != null ? "send succefully!" : "send failed!";
			sendDialog.dismiss();
			page.showToast(msg);
			content.getText().clear();
		}

	};
	OnClickListener replyClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			LayoutInflater factory = LayoutInflater.from(v.getContext());
			View actionView = factory.inflate(R.layout.sendmsgdialog, null);
			if (actionView != null) {
				sendDialog = new AlertDialog.Builder(
						MessageTabFocused.this.page).setTitle("Relpy").setView(
						actionView).show();
				sendBtn = (Button) sendDialog.findViewById(R.id.btnsend);
				sendBtn.setOnClickListener(sendBtnClick);
				EditText userName = (EditText) sendDialog
						.findViewById(R.id.editusername);
				userName.setText(currentSelectUser.getScreen_name());
				content = (EditText) sendDialog
						.findViewById(R.id.editmsgcontent);
				Button cancelBtn = (Button) sendDialog
						.findViewById(R.id.btncancel);
				cancelBtn.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						sendDialog.dismiss();
					}
				});
			}
		}

	};

	public void onScrollStateChanged(AbsListView view, int scrollState) {

	}

	@SuppressWarnings("unchecked")
	private void getUserListAvatar() {

		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				UserInfoModel user = null;
				Bitmap userAvatar = null;
				String urlKey = null;
				SoftReference<Bitmap> bitmapRef;
				for (int i = 0; i < directMessages.size(); i++) {
					user = directMessages.get(i).getSender();
					urlKey = user.getProfile_image_url();
					bitmapRef = (SoftReference<Bitmap>) cache.get(urlKey);
					if (bitmapRef == null) {
						try {
							userAvatar = HttpUtility.getBitmap(urlKey);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						Log.i("sinaweibo", String.format("key is %s", urlKey));
						cache.put(urlKey, userAvatar);
					} else {
						userAvatar = bitmapRef.get();
					}
					if (userAvatar != null) {
						user.setAvatarImg(userAvatar);
						Log.i("sinaweibo", "setUserAvatar");
						userAvatar = null;
					}
				}
				Message message = new Message();
				message.what = 1;
				MessageTabFocused.this.getUserAvatarHandler().sendMessage(
						message);
			}

		}).start();

	}

	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {

	}

	private void filterAndAddMsg() {
		if (directMessagesTemp != null) {
			int len = directMessagesTemp.size();
			DirectMessagesModel msg;
			for (int i = 0; i < len; i++) {
				msg = directMessagesTemp.get(i);
				if (!directMessages.contains(msg)) {
					directMessages.add(FIRST_LOCATION, msg);
				}
			}

		}
	}

	final int VIEWMORE_ID = 101;

	private TextView getViewMoreTextView() {
		return (TextView) listView.findViewById(VIEWMORE_ID);
	}

}
